package com.ruoyi.web.core.wang.utils;

import com.ruoyi.web.core.wang.tool.IncrementNumber;
import jodd.datetime.JDateTime;
import org.apache.commons.lang3.RandomStringUtils;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Author: wangxx
 * @Date: 2018/11/26 9:51
 * @Version 1.0
 */
public class UUIDUtil extends IncrementNumber {
   public static String getUUID(){
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static synchronized String getOrderNo(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        String orderNo = sdf.format(new Date());
        String random = RandomStringUtils.randomNumeric(8);
        return orderNo+random;
    }

    /**
     * 生成下一个需求编号
     */
    public static synchronized String generaterOrderNextNumber(String no) throws ParseException {
        String id = null;
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmm");
        if (no == null) {
            id = "WO"+sdf.format(date)+"0001";
        } else {
            String dateStr = no.substring(2,12);
            JDateTime jdt = new JDateTime(sdf.parse(dateStr));
            int day = jdt.daysBetween(new JDateTime(System.currentTimeMillis()));
            DecimalFormat df = new DecimalFormat("0000");
            if(day>0){
                id = "WO" + sdf.format(date) + "0001";
            }else {
                id = "WO" + sdf.format(date) + df.format(1 + Integer.parseInt(no.substring(12, 16)));
            }
        }
        return id;
    }

    /**
     * 生成下一个需求编号
     */
    public static synchronized String generaterOrderNextNumber(String tag,String no) throws ParseException {
        String id = null;
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmm");
        if (no == null) {
            id = tag+sdf.format(date)+"0001";
        } else {
            String dateStr = no.substring(2,12);
            JDateTime jdt = new JDateTime(sdf.parse(dateStr));
            int day = jdt.daysBetween(new JDateTime(System.currentTimeMillis()));
            DecimalFormat df = new DecimalFormat("0000");
            if(day>0){
                id = tag + sdf.format(date) + "0001";
            }else {
                id = tag + sdf.format(date) + df.format(1 + Integer.parseInt(no.substring(12, 16)));
            }
        }
        return id;
    }




    /**
     * 初始化序列号，从缓存系统中来，比如数据库、文件等
     *
     * @return 初始序列号
     * @throws Exception
     */
    @Override
    public int initStartNum() throws Exception {
        return 0;
    }

    /**
     * 更新区间最大值到缓存系统，比如数据库、文件中。
     *
     * @param intervalMax 区间最大值
     * @throws Exception
     */
    @Override
    public void updateStartNum(int intervalMax) throws Exception {

    }
}
